<?php

namespace app\store\controller\apps\dealer;

use app\store\controller\Controller;
use app\store\model\addons\Modules as ModulesModel;
use think\Db;
/**
 * 应用
 * Class Setting
 * @package app\store\controller\apps\dealer
 */
class Apply extends Controller
{
    /**
     * 应用列表
     * @param string $search
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index($search = '')
    {
        $model = new ModulesModel;
        $list = $model->getList($search)->toArray();
        foreach ($list['data'] as &$item){
            if(file_exists(ADDONS_PATH.$item['identifie'].'/manifest.xml')){
                $maninfest = str_replace("web/../", '', ADDONS_PATH.$item['identifie'].'/manifest.xml');
                $maninfest_content =  ext_addons_manifest($maninfest);
                if($maninfest_content['application']['version']>$item['version']){
                    $item['isupdate'] = true;
                    $item['new_version'] = $maninfest_content['application']['version'];
                }

            }
            unset($item);
        }
        return $this->fetch('index', [
            'list' => $list['data'],
        ]);
    }
    /**
     * 应用未安装列表
     * @param string $search
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function noinstall($search = '')
    {

        $dir=getDir(ADDONS_PATH);
        $plugin_list = array();
        foreach ($dir as $v){
            if(file_exists(ADDONS_PATH.$v.'/manifest.xml')){
                $maninfest = str_replace("web/../", '', ADDONS_PATH.$v.'/manifest.xml');
                $maninfest_content =  ext_addons_manifest($maninfest);
                $manifest_config = manifest_check($v,$maninfest_content);
                if($manifest_config['errno']){
                    $maninfest_content['err_msg'] = $manifest_config['message'];
                }
                $icon = str_replace("web/../", '', ADDONS_PATH.$v.'/icon.jpg');
                if(file_exists($icon)){
                    $maninfest_content['application']['logo'] = 'addons/'.$v.'/icon.jpg';
                }
                $is_modules = ModulesModel::detail(array('identifie'=>$v));
                if(empty($is_modules)){
                    $plugin_list[] = $maninfest_content;
                }
            }

        }
        return $this->fetch('noinstall', [
            'list' => $plugin_list,
        ]);
    }
    /**
     * 卸载模块
     */
    public function uninstall($m_id =''){
        $model = new ModulesModel;
        if(empty($m_id)){
            return  $this->renderError('模块不存在','apps.dealer.apply/index');
        }
        $module = $model->detail(array('m_id'=>$m_id))->toArray();
        if($model->uninstall($m_id)){
            $maninfest = str_replace("web/../", '', ADDONS_PATH.$module['identifie'].'/manifest.xml');
            $maninfest_content =  ext_addons_manifest($maninfest);
            if(!empty($maninfest_content['uninstall'])){
                $uninstall_sql =str_replace('`ims_', '`'.config('database.prefix'), $maninfest_content['uninstall']);
                $uninstall_sql = str_replace(PHP_EOL, '', $uninstall_sql);  //移除换行

                $tableArr = explode(';',$uninstall_sql);
                try{
                    foreach ($tableArr as $tSql){
                        if(!empty($tSql)){
                            Db::execute($tSql);
                        }

                    }
                }catch (\Exception $e){

                    return $this->error($e->getMessage());
                }

            }
           return $this->renderSuccess('卸载成功',url('apps.dealer.apply/index'));
       }else{
           return  $this->renderError('模块卸载失败',url('apps.dealer.apply/index'));
       }

    }
    public function install($modules =''){
        $model = new ModulesModel;
        if(file_exists(ADDONS_PATH.$modules.'/manifest.xml')){
            $maninfest = str_replace("web/../", '', ADDONS_PATH.$modules.'/manifest.xml');
            $maninfest_content =  ext_addons_manifest($maninfest);
            $manifest_config = manifest_check($modules,$maninfest_content);
            if($manifest_config['errno']){
                return $this->renderError($manifest_config['message']);
            }
            $icon = str_replace("web/../", '', ADDONS_PATH.$modules.'/icon.jpg');
            if(file_exists($icon)){
                $maninfest_content['application']['logo'] = 'addons/'.$modules.'/icon.jpg';
            }
            if($model->install($maninfest_content)){
                if(!empty($maninfest_content['install'])){
                    $install_sql =str_replace('`ims_', '`'.config('database.prefix'), $maninfest_content['install']);//兼容某擎ims_
                    $install_sql = str_replace(PHP_EOL, '', $install_sql);  //移除换行
                    $tableArr = explode(';',$install_sql);
                    try{
                        foreach ($tableArr as $tSql){
                            if(!empty($tSql)){
                              Db::execute($tSql);
                            }

                        }
                    }catch (\Exception $e){
                        return $this->error($e->getMessage());//待解决
                    }


                }
                return $this->renderSuccess('安装成功','apps.dealer.apply/index');
            }else{
                return $this->renderError('安装失败',url('apps.dealer.apply/noinstall'));
            }

            return $this->fetch('install', [
                'manifest_config' => $maninfest_content,
            ]);

        }else{
            return $this->renderError('模块不存在manifest.xml',url('apps.dealer.apply/noinstall'));
        }

    }

    public function update($modules=''){
        $model = new ModulesModel;
        require_once WEB_PATH.'/extend/we/loader.class.php';
        load()->func('pdo');
        if(file_exists(ADDONS_PATH.$modules.'/manifest.xml')){
            $module_path =  str_replace("web/../", '', ADDONS_PATH.$modules.'/');
            $maninfest = str_replace("web/../", '', ADDONS_PATH.$modules.'/manifest.xml');
            $maninfest_content =  ext_addons_manifest($maninfest);
            $manifest_config = manifest_check($modules,$maninfest_content);

            if($manifest_config['errno']){
                return $this->renderError($manifest_config['message']);
            }
            $icon = str_replace("web/../", '', ADDONS_PATH.$modules.'/icon.jpg');
            if(file_exists($icon)){
                $maninfest_content['application']['logo'] = 'addons/'.$modules.'/icon.jpg';
            }
            $module_identifie = $model->detail(array('identifie'=>$modules))->toArray();
            $m_id = $module_identifie['m_id'];
            $model->uninstall($m_id);
            if($model->install($maninfest_content)){
                if(!empty($maninfest_content['upgrade'])){
                    if (strexists($maninfest_content['upgrade'], '.php')) {
                        if (file_exists($module_path . $maninfest_content['upgrade'])) {
                            include_once $module_path . $maninfest_content['upgrade'];
                        }
                    } else {
                        Db::execute($maninfest_content['upgrade']);
                    }

                }
                return $this->renderSuccess('更新成功','apps.dealer.apply/index');
            }else{
                return $this->renderError('更新失败',url('apps.dealer.apply/noinstall'));
            }

            return $this->fetch('install', [
                'manifest_config' => $maninfest_content,
            ]);

        }else{
            return $this->renderError('模块不存在manifest.xml',url('apps.dealer.apply/noinstall'));
        }
    }

}